package com.kye.express.business.jd.goods_all_category;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;

import com.kye.base.Logger;
import com.kye.base.utils.NetworkMonitorUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.business.jd.goods_list_by_category.JDGoodsListByCategoryActivity;
import com.kye.express.databinding.ActivityJdAllcategoryBinding;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.jd.shop.JDGoodsCategoryBean;
import com.kye.model.constant.Constants;

import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 京东兑换-全部分类 Activity
 * <p>
 * Created by SkyYu on 2018/1/31
 */
public class JDAllCategoryActivity extends BaseToolbarActivity implements JDAllCategoryConstract.JDAllCategoryView, JDAllCategoryViewBinder.OnCategoryItemListener {

    private final static String TAG_EXCHANGE_RATE = "TAG_EXCHANGE_RATE";
    private JDAllCategoryConstract.JDAllCategoryPresenter mPresenter;
    private ActivityJdAllcategoryBinding mBinding;
    private MultiTypeAdapter mAdapter;
    private double exchangeRate;

    public static void startActivity(Context context, double exchangeRate) {
        Intent intent = new Intent(context, JDAllCategoryActivity.class);
        intent.putExtra(TAG_EXCHANGE_RATE, exchangeRate);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            exchangeRate = getIntent().getDoubleExtra(TAG_EXCHANGE_RATE, 1);
        } else {
            exchangeRate = savedInstanceState.getDouble(TAG_EXCHANGE_RATE);
        }
        initView();
        initEvent();
        initData();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putDouble(TAG_EXCHANGE_RATE, exchangeRate);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mPresenter) mPresenter.unbind();
    }

    private void initView() {
        initBinding();
        initPresenter();
        initToolbar();
    }

    private void initBinding() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_jd_allcategory);
    }

    private void initPresenter() {
        mPresenter = new JDAllCategoryConstract.JDAllCategoryPresenter();
        mPresenter.bind(this);
    }

    private void initToolbar() {
        setUpToolbar(findViewById(R.id.toolbar));
        setTitle(getString(R.string.jd_allcategory));
    }

    private void initData() {
        initAdapter();
        mBinding.statusLayout.showLoadingView();
    }

    private void initAdapter() {
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(JDGoodsCategoryBean.class, new JDAllCategoryViewBinder(this));
        mAdapter.setItems(new Items());
        mBinding.recyclerviewList.setLayoutManager(new GridLayoutManager(this, 4));
        mBinding.recyclerviewList.setItemAnimator(new DefaultItemAnimator());
        mBinding.recyclerviewList.setAdapter(mAdapter);
    }

    private void initEvent() {
        mBinding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                request();
            }
        });
    }

    private void request() {
        NetworkMonitorUtils.networkObservable(this)
                .map((connectivity) -> {
                    NetworkInfo.State state = connectivity.getState();
                    switch (state) {
                        case CONNECTED:
                        case CONNECTING:
                            return true;
                        case DISCONNECTED:
                        case DISCONNECTING:
                            return false;
                        default:
                            return false;
                    }
                })
                .subscribe((Boolean) -> {
                    if (Boolean) {
                        mPresenter.requestToJDGoodsCategories();
                    } else {
                        mBinding.statusLayout.showErrorNetworkView();
                        ToastManager.show(this, getString(R.string.common_net_error));
                    }
                });
    }

    @Override
    public void onSuccessLoadData(OpenApiResult<List<JDGoodsCategoryBean>> result) {
        if (result != null) {
            if (result.getCode() == Constants.ResponseCode_SUCCESS) {
                List<JDGoodsCategoryBean> data = result.getData();
                if (data.size() > 0) {
                    mBinding.statusLayout.showContentView();
                    Items items = (Items) mAdapter.getItems();
                    items.addAll(data);
                    mAdapter.setItems(items);
                    mAdapter.notifyDataSetChanged();
                } else {
                    mBinding.statusLayout.getEmptyTextView();
                }
            } else {
                ToastManager.showCenterForShort(result.getMsg());
            }
        } else {
            Logger.d("JDAllCategoryActivity - onSuccessLoadData - bean is null");
        }
    }

    @Override
    public void onApiError(OpenApiResult<List<JDGoodsCategoryBean>> result, int code, String msg) {
        mBinding.statusLayout.showErrorServerView();
        ToastManager.show(this, msg);
        Logger.d("JDAllCategoryActivity - onApiError - result:" + result + ",code:" + code + ",msg:" + msg);
    }

    @Override
    public void onOtherError(Throwable e) {
        mBinding.statusLayout.showErrorNetworkView();
        ToastManager.show(this, getString(R.string.common_net_error));
        Logger.d("JDAllCategoryActivity - onOtherError : " + e.getMessage());
    }

    @Override
    public void onCategoryItemClicked(JDGoodsCategoryBean item) {
        JDGoodsListByCategoryActivity.startActivity(this, item, exchangeRate);
    }
}